<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Created by JetBrains PhpStorm.
 * User: isra
 * Date: 19/01/13
 * Time: 18:51
 * To change this template use File | Settings | File Templates.
 */
class Login extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
		$this->load->model('login_model');
		$this->load->library(array('session','form_validation'));
		$this->load->helper(array('url','form'));
		$this->load->database('default');
    }
	
	public function index()
	{	
		switch ($this->session->userdata('perfil')) {
			case '':
				$data['token'] = $this->token();
				
				$this->load->model('Evento_model');
				$tipos = $this->Evento_model->getTipos();
				$selectorTipos = array();
				while($tablerow = mysql_fetch_array($tipos)) {
		 			 $selectorTipos[$tablerow['id_tipo']] = $tablerow['nombre'];
				}
				$data['tipos'] = $selectorTipos;

				$categorias = $this->Evento_model->getCategorias();

				$selectorCategorias = array();
				while($tablerow = mysql_fetch_array($categorias)) {
		 			 $selectorCategorias[$tablerow['id_categoria']] = $tablerow['nombre'];
				}
				$data['categorias'] = $selectorCategorias;
		      	
				$listaEventos = $this->Evento_model->getEventos();
	      		$eventos = array('rs_eventos' => $listaEventos);

	      		$datos["inicio"] = 'class="current_page_item"';
				$datos["contact"] = '';
				$datos["unete"] = '';
				$datos["acercaDe"] = '';  
				$v_page["header"] = $this->load->view("header.php", $datos , TRUE);
				$v_page["banner"] = $this->load->view("banner.html", '' , TRUE);
				$v_page["leftside"] = $this->load->view("leftside", $data , TRUE);

				$mostrarEventos["body"] = $this->load->view("mostrar_eventos", $eventos , TRUE);
				$v_page["centralgrid"] = $this->load->view("centralgrid", $mostrarEventos , TRUE);

				$login["body"] = $this->load->view("login_view", $data, TRUE);
				$login["header"] = "Conectate";
				$v_page["rightside"] = $this->load->view("rightside", $login , TRUE);
				
				$v_page["footer"] = $this->load->view("footer.html", '' , TRUE);
				$this->load->view('index', $v_page);
				break;
			case 'administrador':
				redirect(base_url().'index.php/administrador');
				break;
			case 'suscriptor':
				redirect(base_url().'index.php/suscriptor');
				break;
			case 'editor':
				redirect(base_url().'index.php/editor');
				break;	
			default:		
				//$data['titulo'] = 'Login con roles de usuario en codeigniter';
				$this->load->view('login_view',$data);
				break;		
		}
	}
	
	public function token()
	{
		$token = md5(uniqid(rand(),true));
		$this->session->set_userdata('token',$token);
		return $token;
	}
	
	public function new_user()
	{
		if($this->input->post('token') && $this->input->post('token') == $this->session->userdata('token'))
		{
            $this->form_validation->set_rules('username', 'nombre de usuario', 'required|trim|min_length[1]|max_length[150]|xss_clean');
            $this->form_validation->set_rules('password', 'password', 'required|trim|min_length[1]|max_length[150]|xss_clean');
 
            //lanzamos mensajes de error si es que los hay
            $this->form_validation->set_message('required', 'El %s es requerido');
            $this->form_validation->set_message('min_length', 'El %s debe tener al menos %s carácteres');
            $this->form_validation->set_message('max_length', 'El %s debe tener al menos %s carácteres');
			
			if($this->form_validation->run() == FALSE)
			{
				$this->index();
			}
			else
			{
				$username = $this->input->post('username');
				$password = sha1($this->input->post('password'));
				$check_user = $this->login_model->login_user($username,$password);

				if($check_user == TRUE)
				{
					$latitud = $this->input->post('latitud');
					$longitud = $this->input->post('longitud');

					if ($latitud == 0 || $longitud == 0)
					{
						$localizacion = mysql_fetch_assoc($this->login_model->getLastUserCoordinates($check_user->id_usuario));
						$latitud = $localizacion["latitud"];
						$longitud = $localizacion["longitud"];
					}

					$data = array(
	                'is_logued_in' 	=> 		TRUE,
	                'id_usuario' 	=> 		$check_user->id_usuario,
	                'perfil'		=>		$check_user->perfil,
	                'username' 		=> 		$check_user->username,
	                'latitud' 		=> 		$latitud,
	                'longitud' 		=> 		$longitud,
	                //'email' 		=> 		$check_user->email,
	                //'fecha_nacimiento' 	=> 		$check_user->fecha_nac,
	                //'localizacion' 	=> 		$check_user->localizacion,
            		);		
					$this->session->set_userdata($data);
					$this->login_model->saveUserCoordinates($check_user->id_usuario, $this->input->post('latitud'), $this->input->post('longitud'));
					$this->index();
				}
			}
		}
		else
		{
			redirect(base_url());
		}
	}

	public function logout_ci()
	{
		$this->session->sess_destroy();
		require "src/fbaccess.php";
		$facebook->destroySession();
		redirect(base_url());
	}
}
